import { _decorator, Component, Node, Prefab, instantiate, director } from 'cc';
import { EquitmentData } from '../Equitment';
import { EquitmentManager } from '../EquitmentManager';
import { EventManager } from '../EventManager';
import { EventType } from '../EventType';
import { GameManager } from '../GameManager';
import { UIManager } from '../UIManager';
import { UIChestItem } from './UIChestItem';
import { UIConfig } from './UIConfig';
const { ccclass, property } = _decorator;

@ccclass('UIOpenChest')
export class UIOpenChest extends Component {

    @property(Prefab)
    public ChestItemPrefab:Prefab
    @property(Node)
    public ChestArea:Node

    private curChestCount:number = 0
    private curItems:Array<Node>

    start() {
        this.curChestCount = GameManager.instance.ChestLootCount
        GameManager.instance.ChestLootCount = 0
        this.curItems = new Array()
        this.OpenChest()

        EventManager.instance.RegisterEvent(EventType.EquitmentSelect, this.OnSelectEquit,this)
        
    }

    OpenChest()
    {
        if (this.curChestCount <= 0) {
            return
        }
        let equits = EquitmentManager.instance.RandomEquitment(3)
        for (let index = 0; index < equits.length; index++) {
            let chest = instantiate(this.ChestItemPrefab)
            let data = EquitmentData.Data[equits[index]]
            chest.name = data.Name
            chest.parent = this.ChestArea
            chest.getComponent(UIChestItem).SetConfig(data)
            this.curItems.push(chest)
        }
        this.curChestCount --
    }

    OnSelectEquit(nEquitID)
    {
        if(this.curChestCount > 0)
        {
            for (let index = 0; index < this.curItems.length; index++) {
                this.curItems[index].destroy()
            }
            this.OpenChest()
        }
        else
        {
            console.log("[OpenChest] 箱子开完了")
            GameManager.instance.IsGamePause --
            // UIManager.instance.OpenUI(UIConfig.Result)
            this.node.destroy()
        }
    }

    onDestroy()
    {
        EventManager.instance.DeleteEvent(EventType.EquitmentSelect, this.OnSelectEquit,this)
    }

}


